package com.clear.honghefinance.wechat.service.impl;

import com.clear.honghefinance.wechat.config.wechat.WechatConfig;
import com.clear.honghefinance.wechat.service.WechatMpEventService;
import com.clear.honghefinance.wechat.util.SHA1Util;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Slf4j
public class WechatMpEventServiceImpl implements WechatMpEventService {

    @Resource
    private WechatConfig wechatConfig;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 接收微信事件推送、接收微信公众号推送事件
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return 验证结果
     */
    @Override
    public boolean receiveMpEvent(String signature, String timestamp, String nonce) {
        log.info("验签中.. signature:{}, token:{}, timestamp:{}, nonce:{}, echostr:{}",
                signature, wechatConfig.getMp().getToken(), timestamp, nonce);
        String tmpStr = SHA1Util.getSHA1(wechatConfig.getMp().getToken(), timestamp, nonce, "");
        // 【timestamp+token+nonce+密文(可选)】做SHA1摘要签名后与signature对比，一致则验证成功
        if (signature.equals(tmpStr)) {
            log.info("验证成功");
            return true;
        }
        log.error("验证失败");
        return false;
    }

    @Override
    public void receiveMpEvent(Map<String, String> messageMap) {
        // 2、根据推送事件的不同进行分别处理
        if ("subscribe".equals(messageMap.get("Event"))) {
            log.info("订阅事件");
            //  EventKey=qrscene_ScanReg_wx347b3b2a761d0276_dcafeac6f9d941c5a96f97d69783e54c, Event=subscribe
            // a.解析EventKey
            // 在生成带场景二维码时：scene_str 场景值ID：ScanReg_appId_clientId

            // todo 后期也可以优化为使用Redis的发布订阅、MQ等
            // b.发布事件
            if (log.isInfoEnabled()) {
                log.info("发布消息：{}", new Gson().toJson(messageMap));
            }
            rocketMQTemplate.asyncSend("wx-event", messageMap, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息发送成功");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送失败");
                }
            });

        } else if ("SCAN".equals(messageMap.get("Event"))) {
            log.info("扫描事件");
            // EventKey=ScanReg_wx347b3b2a761d0276_dcafeac6f9d941c5a96f97d69783e54c, Event=SCAN
            if (log.isInfoEnabled()) {
                log.info("发布消息：{}", new Gson().toJson(messageMap));
            }
            rocketMQTemplate.asyncSend("wx-event", messageMap, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息发送成功");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送失败");
                }
            });
        } else if ("unsubscribe".equals(messageMap.get("Event"))) {
            log.info("取消订阅事件");
        } else {
            log.info("其他消息，消息类型为:{}", messageMap.get("MsgType"));
            // 其他消息类型，如text、image、voice、vide等，留作扩展
        }
    }
}
